package org.yxing.palpalgps.activity;

import java.io.File;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.yxing.palpalgps.AbstractActivity;
import org.yxing.palpalgps.ActionBar;
import org.yxing.palpalgps.ActionBar.OnActionBarListener;
import org.yxing.palpalgps.PalPalGPSApplication;
import org.yxing.palpalgps.R;
import org.yxing.palpalgps.adapter.PhotoAdapter;
import org.yxing.palpalgps.http.AsyncUpload;
import org.yxing.palpalgps.http.AsyncUpload.OnUploadListener;
import org.yxing.palpalgps.oauth.OAuth;
import org.yxing.palpalgps.utils.Helper;
import org.yxing.palpalgps.utils.Utils;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

public class PhotoGridActivity extends AbstractActivity implements AdapterView.OnItemClickListener, OnActionBarListener{
    private static final String TAG = PhotoGridActivity.class.getSimpleName();
    private static final int IS_REFLASH = 0;
    private static final int FACE_CAMERA_RESULT = 1;
    private static final int FACE_ALBUM_RESULT = 2;
    private static final int FACE_CROP = 4;
    public static final String TAG_REFLASH = "reflash";
    
    /**
     * temp dir for save temp photo
     */
    private File sdcardTempDir;
    
    /**
     * temp photo file name
     */
    private File sdcardTempfile;
    
    private File photoFile;
    
    private boolean hasSDCard;
    
    private GridView mGridView;
    
    private PhotoAdapter mPhotoAdapter;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_grid);
        setTitle(getString(R.string.photos_grid));
        
        addActionBarItem(ActionBar.Type.Refresh);
        addActionBarItem(ActionBar.Type.Add);
        getActionBar().setOnActionBarListener(this);
        
        mGridView = (GridView) findViewById(R.id.gridView);
        mPhotoAdapter = new PhotoAdapter(this);
        mGridView.setAdapter(mPhotoAdapter);
        mGridView.setOnItemClickListener(this);
        refresh();
        
        hasSDCard = Utils.hasSDCard();
    }
    
    private void refresh() {
        mPhotoAdapter.loadData();
    }
    
    public void onResume() {
        super.onResume();
    }
    
    public void onItemClick(AdapterView<?> parend, View view, int position,long id) {
//        Intent intent = new Intent(this, PhotoViewActivity.class);
    	Intent intent = new Intent(this, PhotoGalleryActivity.class);
        intent.putExtra("id", (int)id);
        intent.putStringArrayListExtra("data", mPhotoAdapter.getItems());
        startActivityForResult(intent, IS_REFLASH);
    }

    public void onActionBarItemClick(int position) {
        switch (position) {
        case 0:
            refresh();
            break;
        case 1:
            Add();
            break;
        }
    }
    
    /**
     * 启动添加一张新照片
     */
    private void Add() {
        if (hasSDCard) {
            if (sdcardTempDir == null)
                sdcardTempDir = new File(Environment.getExternalStorageDirectory()+ File.separator + PalPalGPSApplication.SDCARD_DIR);
            createDialogForAddPhoto();
            if (photoFile == null) {
                photoFile = new File(sdcardTempDir, PalPalGPSApplication.SDCARD_PROTRAIT_FILENAME);
            }
        } else {
            displayToast(getString(R.string.toast_no_sdcard));
        }
    }
    
    /**
     * start up camera
     */
    private void startUpCamera() {
        sdcardTempfile = new File(sdcardTempDir, System.currentTimeMillis() + ".jpg");
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri uri = Uri.fromFile(sdcardTempfile);
        intent.putExtra("output", uri);
        startActivityForResult(intent, FACE_CAMERA_RESULT);
    }
    
    /**
     * start up album
     */
    private void startUpAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
        startActivityForResult(intent, FACE_ALBUM_RESULT);
    }
    
    /**
     * crop photo
     * @param uri photo uri
     */
    private void cropImage(Uri uri) {
        if (photoFile.exists())
            photoFile.delete();
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", Helper.PICTURE_SIZE_BIG);
        intent.putExtra("outputY", Helper.PICTURE_SIZE_BIG);
        intent.putExtra("noFaceDetection", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
        startActivityForResult(intent, FACE_CROP);

    }
    
    private void uploadPhoto() {
        if (sdcardTempfile.exists())
            sdcardTempfile.delete();
        
        final List<BasicNameValuePair> params = OAuth.createAuthParams();
        AsyncUpload au = new AsyncUpload(this);
        au.setOnUploadListener(new OnUploadListener() {
            
            public void onError() {
                
            }
            
            public void onComplate(String result) {
                Log.d(TAG, result);
                refresh();
            }
        });
        //上传照片
        au.upload(Helper.getAppUrl("photo/upload"), params, photoFile, "photo");
    }
    
    private void createDialogForAddPhoto() {
        String[] items = new String[]{getString(R.string.camera_piciture), getString(R.string.album_piciture)};
        
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
            .setTitle(getString(R.string.select_face_image))
            .setItems(items, new DialogInterface.OnClickListener() {
                
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent;
                    switch(which) {
                    case 0:
                        startUpCamera();
                        break;
                    case 1:
                        startUpAlbum();
                        break;
                    }
                }
            });
        builder.show();
    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
            case IS_REFLASH:
                if (data.getBooleanExtra(TAG_REFLASH, false))
                    refresh();
                break;
            case FACE_ALBUM_RESULT:
                cropImage(data.getData());
                break;
            case FACE_CAMERA_RESULT:
                cropImage(Uri.fromFile(sdcardTempfile));
                break;
            case FACE_CROP:
                uploadPhoto();
                break;
            }
        }
    }
}
